#include <cstring>
#include <fstream>
#include <iostream>
using namespace std;

#define N 3

class Student
{
public:
	Student()
	{
		name[0]  = '\0';
		age = 0;
	}

	Student(const char *_name, int _age)
	{
		strcpy(name, _name);
		age = _age;
	}

	void setAge(int _age)
	{
		age = _age;
	}

	friend ostream& operator<<(ostream&, const Student&);
private:
	//string name;
	char name[30];
	int age;
};

//重载插入运算符 << 
ostream& operator<<(ostream& output, const Student& stu)
{
	output << "name:" << stu.name << "\tage:" << stu.age;
	return output;
}

int main()
{
	//cout << sizeof(Student) << endl;
	
	Student stu[N] = {
		Student("zhangsan", 20),
		Student("lisi", 22),
		Student("wangwu", 18)};

	//------写文件-------
	ofstream outfile("student.dat", ios::out | ios::binary);	//

	if (!outfile)
	{
		cerr << "open file error!";
		exit(1);
	}

	for(int i = 0; i < N; ++i)
	{
		outfile.write((char*)&stu[i], sizeof(stu[i]));			//写入数据
	}

	outfile.close();
	
	//------读文件 全部记录------
	Student stu2[N];
	ifstream infile("student.dat", ios::in | ios::binary);
	if (!infile)
	{
		cerr << "open file error!";
		exit(1);
	}

	cout << "读取文件信息：" << endl;

	i = 0;
	while(infile.read((char*)&stu2[i], sizeof(stu2[i])))
	{
		cout << stu2[i] << endl;
	}

	infile.close();

	//------修改数据  读取wangwu信息, 修改年龄后，再写入文件------
	
	Student wangwu;
	fstream file("student.dat", ios::in | ios::out | ios::binary); 
	if (!file)
	{
		cerr << "open file error!";
		exit(1);
	}

	file.seekp(sizeof(Student) * 2, ios::beg);		//移动文件指针
	file.read((char*)&wangwu, sizeof(Student));		//读取wangwu信息
	cout << "\n修改前：\n" << wangwu << endl;

	wangwu.setAge(19);		//修改wangwu年龄			
		
	file.seekp(-sizeof(Student), ios::cur);			//从当前位置向前移动指针 ==	file.seekp(sizeof(Student) * 2, ios::beg);
	file.write((char*)&wangwu, sizeof(Student));	//写入数据

	file.seekp(-sizeof(Student), ios::cur);			//从当前位置向前移动指针
	file.read((char*)&wangwu, sizeof(Student));		//重新读取wangwu信息
	cout << "\n修改后：\n" << wangwu << endl;

	file.close();

	return 0;
}

